const q = (css, p = document) => p.querySelector(css);
const playPage = chrome.runtime.getURL('play.html');
const vKind = { 1:'normal',2:'hls',4:'dash',8:'flv' };
let mvList;
const check0ConvertKind = t => {
	if (!t) return '未知';
	if (typeof t == 'number') return vKind[t] || 'auto';
	if (t.startsWith('video')) return 'normal';
	return t;
};
const getFileName = url => {
	let i, n = url.indexOf('?',33);
	if (-1 != n) i = n-3;
	else {
		i = url.length - 4;
		n = void 0;
	}
	i = url.lastIndexOf('.',i) +1;
	if (!i) return;
	i = url.lastIndexOf('/',i-3) +1;
	return url.slice(i, n);
};
const toByteUnit = bytes => { // 数字转换为字节（单位）显示 Number.MAX_SAFE_INTEGER
	if (!bytes) return '未知';
	bytes = +bytes;
	if (bytes < 1024) return bytes +'B';
	const symbols = Array.from('BKMGTPEZYB');
	const exp = ~~(Math.log(bytes)/Math.log(2));
	const i = ~~(exp / 10);
	bytes /= Math.pow(2, 10 * i);
	bytes = bytes.toFixed(2).replace(/\.?0+$/,'');
	return `${bytes}${symbols[i]}B`;
};
const fillTable = a => {
	mvList = a;
	q('dl').innerHTML = a.reduce((affix, k, i, arr) => {
		let lastDD = '播放';
		const kind = check0ConvertKind(k.kind);
		if (kind.startsWith('audio/')) {
			const fn = getFileName(k.url) || 'music_xx' + i;
			lastDD = `<a href="${k.url}" download="${fn}">下载</a>`;
		}
		return `${affix}<dt>${k.url}</dt><dd class="idx">${i+1}</dd><dd>类型:${kind}</dd><dd>大小:${toByteUnit(k.size)}</dd><dd index="${i}" class="last-col">${lastDD}</dd>`;
	}, '');
};
function copyToClipboard(textToCopy) {
	// navigator clipboard 需要https等安全上下文
	if (navigator.clipboard && window.isSecureContext) return navigator.clipboard.writeText(textToCopy);

	const textArea = document.createElement("textarea");
	textArea.value = textToCopy;
	textArea.style.position = "absolute";
	textArea.style.top = "-999999px";
	document.body.appendChild(textArea);
	textArea.focus();
	textArea.select();
	return new Promise((res, rej) => {
		document.execCommand('copy') ? res() : rej();
		textArea.remove();
	});
}

q('dl').addEventListener('click', ev => {
	const e = ev.target;
	if (e.tagName == 'A') return;
	if (e.tagName == 'DT') {
		navigator.clipboard.writeText(e.textContent);
	}
	else if (e.matches('.last-col')) {
		const i = e.getAttribute('index') | 0;
		let t = check0ConvertKind(mvList[i].kind);
		if (t.startsWith('audio')) return;
		const kind = { normal:1,hls:2,dash:4,flv:8,auto:-1 };
		if (!kind[t]) t = 'auto';
		const url = `${playPage}?vType=${t}#${mvList[i].url}`;
		chrome.tabs.create({url});
	}
});

chrome.tabs.query({currentWindow:true,active:true}, function(tabs) {
	if (tabs[0].url.startsWith('http')) {
		chrome.runtime.sendMessage({id:'getMVList', tabId: tabs[0].id}, fillTable);
	}
});